package name.vaccari.matteo.tai.phonedirectory.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer extends Thread {

	private final int port;
	private ServerSocket serverSocket;
	private boolean isClosing;
	private final Protocol protocol;

	public TcpServer(int port, Protocol protocol) {
		this.port = port;
		this.protocol = protocol;
	}
	
	@Override
	public void run() {
		try {
			serverSocket = new ServerSocket(port);
			while (true) {
				Socket client = serverSocket.accept();
				protocol.process(client.getInputStream(), client.getOutputStream());
				client.close();
			}
		} catch (IOException e) {
			if (!isClosing) {
				e.printStackTrace();
			}
		}
	}


	public void close() {
		try {
			this.isClosing = true;
			serverSocket.close();
		} catch (IOException ignored) {
		}
	}

}
